<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="客户名称" prop="userId" v-show="!flag">
        <el-select
          v-model="formData.userId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入客户名称"
          :remote-method="querySearchCustomer"
          :loading="searchCustomerLoading"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否充值" prop="isAdd">
        <el-radio-group v-model="formData.isAdd">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="充值金额" prop="activityMoney" v-if="formData.isAdd === 1">
        <el-input-number controls-position="right" :min="0" v-model="formData.activityMoney" placeholder="请输入充值金额">
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="消费类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio :value="1">返现</el-radio>
          <el-radio :value="2">退货</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="useMoney">
        <template #label>
          <template v-if="formData.type === 1">返现金额</template>
          <template v-else>退货金额</template>
        </template>
        <el-input-number controls-position="right" :min="0" v-model="formData.useMoney" placeholder="请输入消费、退货金额">
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="取货时间" prop="pickUpTime">
        <el-date-picker
          v-model="formData.pickUpTime"
          type="date"
          value-format="x"
          placeholder="选择取货时间"
        />
      </el-form-item>
      <el-form-item label="取货描述" prop="pickUpDesc">
        <el-input type="textarea" v-model="formData.pickUpDesc" placeholder="请输入取货描述" />
      </el-form-item>
      <el-form-item label="取货签名" prop="userSign">
        <Editor v-model="formData.userSign" :height="300" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ActivityUserApi, ActivityUserVO } from '@/api/erp/activityuser'
import {CustomerApi, CustomerVO} from "@/api/erp/sale/customer";

/** 用户参与活动 表单 */
defineOptions({ name: 'ActivityUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  activityId: undefined,
  userId: undefined,
  activityMoney: 0,
  pickUpTime: undefined,
  pickUpDesc: undefined,
  userSign: undefined,
  type: 1,
  useMoney: 0,
  isAdd: 1
})
const formRules = reactive({
  activityId: [{ required: true, message: '活动id不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
  activityMoney: [{ required: true, message: '首次参与活动付出金额不能为空', trigger: 'blur' }],
  pickUpTime: [{ required: true, message: '取货时间不能为空', trigger: 'blur' }],
  pickUpDesc: [{ required: true, message: '取货描述不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '消费类型 1消费 2退货不能为空', trigger: 'blur' }],
  useMoney: [{ required: true, message: '消费、退货金额不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const flag = ref(false)
/** 打开弹窗 */
const open = async (type: string, activityId: number, userId: number, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.activityId = activityId
  formData.value.userId = userId
  if (formData.value.userId > 0) {
    flag.value = true
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ActivityUserApi.getActivityUserJoinInfo(id)
      if (formData.value.activityMoney <= 0) {
        formData.value.isAdd = 0
      } else {
        formData.value.isAdd = 1
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ActivityUserVO
    if (formType.value === 'create') {
      await ActivityUserApi.createActivityUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await ActivityUserApi.updateActivityUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const searchCustomerLoading = ref(true)
const querySearchCustomer = async (queryString: string) => {
  searchCustomerLoading.value = true
  customerList.value = []
  try {
    if (queryString.length > 0) {
      let list = await CustomerApi.getCustomerPage({
        pageSize: 100, pageNum: 1, name: queryString
      })

      list.list.forEach((item) => {
        customerList.value.push({
          id: item.id,
          name: item.name,
          mobile: item.mobile
        })
      })
    }
  } finally {
    searchCustomerLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    activityId: undefined,
    userId: undefined,
    activityMoney: 0,
    pickUpTime: undefined,
    pickUpDesc: undefined,
    userSign: undefined,
    type: 1,
    useMoney: 0,
    isAdd: 1
  }
  formRef.value?.resetFields()
}
</script>
